<script lang="ts" setup name="StockPlanEdit">
import { Minus, Plus } from '@element-plus/icons-vue'
import { FormInstance, FormRules } from 'element-plus'
import { ProTableInstance } from '~/library/components/ProTable/interface'
import SelectTreeTable from '~/library/components/SelectTreeData/index.vue'
import { getWaresCategoryListAPI } from '~/src/api/goods'
import { Procure } from '~/src/api/interface/procure'
import {
  checkStockPlanAPI,
  createStockPlanAPI,
  editStockPlanAPI,
  getStockPlanGoodsDetailAPI,
  getStockPlanGoodsListAPI,
  getStoreHouseAPI,
} from '~/src/api/procure'
import { detailTypeNameType } from '~/src/utils/serviceDict'
import { stockPlanAddColumn } from './info/columns'

const activeName = ref('first')
const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const proTableRef = ref<ProTableInstance>()

const stockPlanForm = ref<Procure.StockPlan>({
  id: 0,
  checkFlag: false,
  houseId: 518161850568773,
  inventoryplandetailList: [],
  isClean: false,
  orderId: 0,
  orderNo: '',
  remark: '',
  status: 1,
  sysUserId: 0,
  detailType: '',
})
const planRules = reactive<FormRules>({})

const documentStatus = ref('add')
onMounted(() => {
  documentStatus.value = route.query.type as string
  stockPlanForm.value.orderId = route.query.id as number | string
  onShowStore()
})
const summary = ref<any[]>([])
const dataCallback = (data: any) => {
  summary.value = data.summary
  stockPlanForm.value.inventoryplandetailList = data.list
  return {
    list: data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize,
  }
}
// 合计数据
const getSummaries = () => summary.value

const initParam = reactive({ id: route.query?.id, detailType: stockPlanForm.value.detailType })
// 查看状态数据
const searchResult = () => {
  initParam.detailType = stockPlanForm.value.detailType
  proTableRef.value?.getTableList()
}

const storeList = ref<any[]>([])
const onShowStore = async () => {
  const res = await getStoreHouseAPI({ pageSize: 9999, pageNum: 1 })
  storeList.value = res.data.list
  storeList.value.forEach((v) => {
    if (v.isDefault) {
      stockPlanForm.value.houseId = v.id
    }
  })
}
const selectChange = () => {
  stockPlanForm.value.inventoryplandetailList = []
}

// 打开库存商品弹出层列表
const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null)
const openSelectTreeTable = (title: string, searchVal?: string | number) => {
  if (!stockPlanForm.value.houseId) return ElMessage.error('请先选择仓库')
  const params = {
    title,
    isView: false,
    searchVal,
    index: 0,
    selType: 'selection',
    mate: 'productsId',
    selTags: stockPlanForm.value.inventoryplandetailList
      .filter((age: any) => age.goodsId !== 0)
      .map((i: any) => {
        i.name = i.name
        i.id = i.prodcutId
        return i
      }),
    columns: [
      { type: 'selection', width: 80 },
      { prop: 'barcode', label: '编码', align: 'left', minWidth: 220 },
      { prop: 'name', label: '商品名称', align: 'left', minWidth: 220 },
      { prop: 'productName', label: '规格', align: 'left', minWidth: 100 },
      { prop: 'unitName', label: '单位', align: 'left', minWidth: 100 },
      // { prop: "posPrice", label: "商品价格", minWidth: 120 }
      { prop: 'purPrice', label: '采购价格', minWidth: 120 },
    ],
    apiParams: { houseId: stockPlanForm.value.houseId },
    idName: 'goodsCategoryId',
    // 发请求
    treeApi: getWaresCategoryListAPI,
    api: getStockPlanGoodsListAPI,
  }
  selectTreeTableRef.value?.acceptParams(params)
}
const delSpecRow = (index: number) => {
  if (stockPlanForm.value.inventoryplandetailList.length <= 1) return ElMessage.error('商品不能少于一条数据')
  stockPlanForm.value.inventoryplandetailList.splice(index, 1)
}

// 选中库存商品
const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list: Procure.StockPlanGoodsDetail[] = val.list.map((im: any) => {
      return {
        name: im.name,
        id: im.id,
        storeId: im.storeId,
        corpId: im.corpId,
        productsId: im.productsId,
        productName: im.productName,
        goodsId: im.id,
        quantity: im.planQuantity,
        price: im.costPrice,
        barcode: im.barcode,
        unitName: im.unitName,
        categoryName: im.categoryName,
        costAmount: im.costAmount,
      }
    })

    list.forEach((v) => {
      if (!stockPlanForm.value!.inventoryplandetailList.some((i: any) => i.productsId === v.productsId)) {
        stockPlanForm.value!.inventoryplandetailList.push(v)
      }
    })
  }
}

const onCheckSubmit = async () => {
  await checkStockPlanAPI({ id: route.query?.id })
  ElMessage.success('成功完成盘点')
  router.push({ path: '/procure/stockPlan' })
}

const onSubmit = async () => {
  if (route.query.id && +route.query.id) {
    await editStockPlanAPI(stockPlanForm.value)
    router.push({ path: '/procure/stockPlan' })
  } else {
    if (stockPlanForm.value.inventoryplandetailList < 1) return ElMessage.error('商品明细不能为空')
    await createStockPlanAPI(stockPlanForm.value)
    router.push({ path: '/procure/stockPlan' })
  }
}
</script>

<template>
  <div class="auto-height-container default-table-container">
    <div class="table-container">
      <header-line
        :confirmIsSHow="documentStatus !== 'audited'"
        :title="(route.query.id && +route.query.id ? '编辑' : '新增') + '盘点计划'"
        @on-submit="onSubmit()"
      >
        <template #button>
          <el-button type="primary" @click="openSelectTreeTable('选择商品')">添加商品明细</el-button>
          <el-button type="primary" @click="searchResult">查询盘点结果</el-button>
          <el-button v-if="stockPlanForm.status === 2" type="primary" @click="onCheckSubmit">完成盘点</el-button>
        </template>
      </header-line>
    </div>

    <el-form ref="ruleFormRef" :inline="true" label-width="120px" :model="stockPlanForm" :rules="planRules">
      <el-form-item label="单据号" prop="orderNo">
        <el-input v-model="stockPlanForm.orderNo" class="width160" disabled placeholder="系统自动生成" />
      </el-form-item>
      <!-- <el-form-item label="盘点范围" prop="planType">
        <el-select class="width150" v-model="stockPlanForm.planType" :disabled="documentStatus !== 'add'">
          <el-option v-for="item in typeScopeList" :label="item.label" :value="item.value" :key="item.value" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="仓库" prop="houseId">
        <el-select v-model="stockPlanForm.houseId" class="width150" :disabled="documentStatus !== 'add'" @change="selectChange">
          <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="stockPlanForm.remark"
          class="width150"
          :disabled="documentStatus === 'audited'"
          placeholder="请填写"
          :rows="1"
          type="textarea"
        />
      </el-form-item>

      <!-- 只要未审核都要显示盘点清零 -->
      <el-form-item label="漏盘清零">
        <el-checkbox v-model="stockPlanForm.isClean" :disabled="stockPlanForm.status === 4" />
      </el-form-item>

      <!-- 审查完查询状态 -->
      <el-form-item v-if="documentStatus !== 'add'" label="盘点结果" prop="detailType">
        <el-select v-model="stockPlanForm.detailType" class="width150">
          <el-option v-for="item in detailTypeNameType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <pro-table
      v-if="documentStatus === 'add'"
      ref="proTableAdd"
      :columns="stockPlanAddColumn"
      :data="stockPlanForm.inventoryplandetailList"
      :is-card="false"
      :pagination="false"
      row-key="id"
      :toolButton="false"
    >
      <template #operate="scope">
        <div class="flx-justify-between">
          <el-button :icon="Plus" link type="primary" @click="openSelectTreeTable('选择商品')" />
          <el-button :icon="Minus" link @click="delSpecRow(scope.$index)" />
        </div>
      </template>
    </pro-table>
    <pro-table
      v-else
      ref="proTableRef"
      :columns="stockPlanAddColumn"
      :data-callback="dataCallback"
      :init-param="initParam"
      :is-card="false"
      :request-api="getStockPlanGoodsDetailAPI"
      row-key="id"
      :show-summary="documentStatus === 'audited'"
      :summary-method="getSummaries"
      :toolButton="false"
    />

    <select-tree-table ref="selectTreeTableRef" @selected-list="handleSelectedTreeList" />
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-table thead .el-table__cell) {
  padding: 5px 0;
  background: #f2f3f5;
}
:deep(.el-table tfoot .el-table__cell) {
  padding: 5px 0;
  background: #f2f3f5;
}
:deep(.el-table .el-table__cell) {
  padding: 0;
}
:deep(.el-form-item) {
  margin-bottom: 8px;
}
</style>
